package top.zywork.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.zywork.annotation.SysLog;
import top.zywork.common.BeanUtils;
import top.zywork.common.BindingResultUtils;
import top.zywork.common.StringUtils;
import top.zywork.constant.CommonConstant;
import top.zywork.dos.SchoolDO;
import top.zywork.dto.PagerDTO;
import top.zywork.dto.GraphicDTO;
import top.zywork.ext.dos.GraphicExtDO;
import top.zywork.ext.dos.GraphicPreferentialExtDO;
import top.zywork.ext.dos.GraphicWalletExtDO;
import top.zywork.ext.service.GraphicExtService;
import top.zywork.ext.service.GraphicPreferentialExtService;
import top.zywork.ext.service.GraphicWalletExtService;
import top.zywork.query.GraphicQuery;
import top.zywork.service.GraphicService;
import top.zywork.service.SchoolService;
import top.zywork.vo.ResponseStatusVO;
import top.zywork.vo.PagerVO;
import top.zywork.vo.GraphicVO;
import top.zywork.wx.response.GraphicResponse;
import top.zywork.wx.response.GraphicSelectResponse;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * GraphicController控制器类<br/>
 *
 * 创建于2020-11-25<br/>
 *
 * @author http://ljyanimo.com 刘金泳
 * @version 1.0
 */
@RestController
@RequestMapping("/graphic")
@Slf4j
public class GraphicController extends BaseController {

    private GraphicService graphicService;

    @Autowired
    private GraphicExtService graphicExtService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private GraphicWalletExtService graphicWalletExtService;

    @Autowired
    private GraphicPreferentialExtService graphicPreferentialExtService;

    /**
     * 获取图文店list
     * @return
     */
    @GetMapping("/any/getList")
    public ResponseStatusVO getList(){
        List<GraphicExtDO> graphicExtDOS = graphicExtService.list();

        List<GraphicSelectResponse> list;

        list = graphicExtDOS.stream().map(e->{
            GraphicSelectResponse graphicSelectResponse = new GraphicSelectResponse();
            org.springframework.beans.BeanUtils.copyProperties(e,graphicSelectResponse);
            return graphicSelectResponse;
        }).collect(Collectors.toList());

        return ResponseStatusVO.ok("查询成功",list);

    }

    /**
     * 根据学校id获取list图文店
     * @return
     */
    @GetMapping("any/list/{schoolId}")
    public ResponseStatusVO list(@PathVariable("schoolId") Integer schoolId){
        List<GraphicExtDO> list = graphicExtService.list(new QueryWrapper<GraphicExtDO>().eq("school_id", schoolId));

        List<GraphicResponse> responseList;
        responseList = list.stream().map(e->{
            GraphicResponse graphicResponse = new GraphicResponse();
            org.springframework.beans.BeanUtils.copyProperties(e,graphicResponse);
            SchoolDO school = schoolService.getById(e.getSchoolId());
            graphicResponse.setSchoolValue(school.getSchool());
            return graphicResponse;

        }).collect(Collectors.toList());

        return ResponseStatusVO.ok("查询成功",responseList);
    }

    @PostMapping("admin/save")
    @SysLog(description = "后台保存GraphicVO")
    @Transactional(rollbackFor = Throwable.class)
    public ResponseStatusVO save(@RequestBody @Validated GraphicVO graphicVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        GraphicExtDO graphicExtDO = BeanUtils.copy(graphicVO, GraphicExtDO.class);
        graphicExtService.save(graphicExtDO);

        int id = graphicExtDO.getId();

        // 创建钱包账户
        GraphicWalletExtDO graphicWalletExtDO = new GraphicWalletExtDO();
        graphicWalletExtDO.setCreateTime(new Date());
        graphicWalletExtDO.setUpdateTime(new Date());
        graphicWalletExtDO.setId(Long.valueOf(id));
        graphicWalletExtDO.setIsActive(CommonConstant.IS_ACTIVE_TRUE);
        graphicWalletExtDO.setUsableRmbBalance(BigDecimal.ZERO);
        graphicWalletExtDO.setVersion(1);

        graphicWalletExtService.save(graphicWalletExtDO);

        // 创建量大优惠
        GraphicPreferentialExtDO graphicPreferentialExtDO = new GraphicPreferentialExtDO();
        graphicPreferentialExtDO.setCreateTime(new Date());
        graphicPreferentialExtDO.setUpdateTime(new Date());
        graphicPreferentialExtDO.setGraphicId(id);
        graphicPreferentialExtDO.setIsActive(CommonConstant.IS_ACTIVE_TRUE);
        graphicPreferentialExtDO.setVersion(1);

        graphicPreferentialExtService.save(graphicPreferentialExtDO);

        return ResponseStatusVO.ok("添加成功", null);
    }

    @PostMapping("admin/batch-save")
    @SysLog(description = "后台批量保存GraphicVO")
    public ResponseStatusVO saveBatch(@RequestBody @Validated List<GraphicVO> graphicVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicService.saveBatch(BeanUtils.copyListObj(graphicVOList, GraphicDTO.class));
        return ResponseStatusVO.ok("批量添加成功", null);
    }

    @GetMapping("admin/remove/{id}")
    @SysLog(description = "后台删除GraphicVO")
    @Transactional(rollbackFor = Throwable.class)
    public ResponseStatusVO removeById(@PathVariable("id") Long id) {
        // 删除图文店数据
        graphicService.removeById(id);
        // 删除图文店总钱包
        graphicWalletExtService.removeById(id);
        // 删除图文店规格
//        graphicSpecExtService.remove(new QueryWrapper<GraphicSpecExtDO>().eq("graphic_id",id));
        return ResponseStatusVO.ok("删除成功", null);
    }

    @PostMapping("admin/batch-remove")
    @SysLog(description = "后台批量删除GraphicVO")
    public ResponseStatusVO removeByIds(@RequestBody String[] ids) {
        graphicService.removeByIds(StringUtils.strArrayToLongArray(ids));
        return ResponseStatusVO.ok("批量删除成功", null);
    }

    @PostMapping("admin/update")
    @SysLog(description = "后台更新GraphicVO")
    public ResponseStatusVO update(@RequestBody @Validated GraphicVO graphicVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        int updateRows = graphicService.update(BeanUtils.copy(graphicVO, GraphicDTO.class));
        if (updateRows == 1) {
            return ResponseStatusVO.ok("更新成功", null);
        } else {
            return ResponseStatusVO.dataError("数据版本号有问题，在此更新前数据已被更新", null);
        }
    }

    @PostMapping("admin/batch-update")
    @SysLog(description = "后台批量更新GraphicVO")
    public ResponseStatusVO updateBatch(@RequestBody @Validated List<GraphicVO> graphicVOList, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResponseStatusVO.dataError(BindingResultUtils.errorString(bindingResult), null);
        }
        graphicService.updateBatch(BeanUtils.copyListObj(graphicVOList, GraphicDTO.class));
        return ResponseStatusVO.ok("批量更新成功", null);
    }

    @PostMapping("admin/active")
    @SysLog(description = "后台激活或冻结GraphicVO")
    public ResponseStatusVO active(@RequestBody GraphicVO graphicVO) {
        graphicService.update(BeanUtils.copy(graphicVO, GraphicDTO.class));
        return ResponseStatusVO.ok("激活或冻结成功", null);
    }

    @PostMapping("admin/batch-active")
    @SysLog(description = "后台批量激活或冻结GraphicVO")
    public ResponseStatusVO activeBatch(@RequestBody @Validated List<GraphicVO> graphicVOList) {
        graphicService.updateBatch(BeanUtils.copyListObj(graphicVOList, GraphicDTO.class));
        return ResponseStatusVO.ok("批量激活或冻结成功", null);
    }

    @GetMapping("admin/one/{id}")
    public ResponseStatusVO getById(@PathVariable("id") Long id) {
        GraphicVO graphicVO = new GraphicVO();
        Object obj = graphicService.getById(id);
        if (obj != null) {
            graphicVO = BeanUtils.copy(obj, GraphicVO.class);
        }
        return ResponseStatusVO.ok("查询成功", graphicVO);
    }

    @GetMapping("admin/all")
    public ResponseStatusVO listAll() {
        PagerDTO pagerDTO = graphicService.listAll();
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GraphicVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/all-cond")
    public ResponseStatusVO listAllByCondition(@RequestBody GraphicQuery graphicQuery) {
        PagerDTO pagerDTO = graphicService.listAllByCondition(graphicQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);
        pagerVO.setRows(BeanUtils.copyList(pagerDTO.getRows(), GraphicVO.class));
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @PostMapping("admin/pager-cond")
    public ResponseStatusVO listPageByCondition(@RequestBody GraphicQuery graphicQuery) {
        PagerDTO pagerDTO = graphicService.listPageByCondition(graphicQuery);
        PagerVO pagerVO = BeanUtils.copy(pagerDTO, PagerVO.class);

        List<Object> list;

        list = pagerDTO.getRows().stream().map(e->{
            GraphicDTO graphicDTO = (GraphicDTO)e;
            graphicDTO.setSchoolValue(schoolService.getById(graphicDTO.getSchoolId()).getSchool());
            return graphicDTO;
        }).collect(Collectors.toList());
        pagerVO.setRows(list);
        return ResponseStatusVO.ok("查询成功", pagerVO);
    }

    @Autowired
    public void setGraphicService(GraphicService graphicService) {
        this.graphicService = graphicService;
    }
}
